<template>
  <div class="custom-flex-cont-vertical">
    <!--搜索条件-->
    <el-form :inline="true" size="mini" class="auto-width-form custom-form">
      <el-form-item label="请求地址">
        <el-input v-model="queryParams.path" placeholder="如：/system/user/list"></el-input>
      </el-form-item>
      <el-form-item label="IP">
        <el-input v-model="queryParams.ip" placeholder="如：127.0.0.1"></el-input>
      </el-form-item>
      <el-form-item label="所属服务">
        <router-select v-model="queryParams.serviceId"></router-select>
      </el-form-item>
      <el-form-item label="请求时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          align="left"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="['8:30:00', '17:30:00']">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query()">查询</el-button>
      </el-form-item>
    </el-form>
    <!--查询结果列表-->
    <div class="custom-flex-cont-vertical fit-all custom-shadow">
      <el-table
        stripe
        v-loading="loading"
        :data="tableData">
        <template slot="empty">
          <empty-tip></empty-tip>
        </template>
        <el-table-column
          align="center"
          type="index"
          width="40">
        </el-table-column>
        <el-table-column
          prop="httpStatus"
          label="响应状态">
          <template slot-scope="scope">
            <span :class="scope.row.httpStatus==='200'?'text-success':'text-danger'">
              <i :class="scope.row.httpStatus==='200'?'el-icon-circle-check':'el-icon-circle-close'"></i>&nbsp;
              {{scope.row.httpStatus}}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          width="300"
          prop="path"
          label="请求地址">
        </el-table-column>
        <el-table-column
          prop="method"
          label="请求方式">
          <template slot-scope="scope">
            <el-tag type="primary" size="small">{{scope.row.method}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="ip"
          label="IP"
          width="100">
          <template slot-scope="scope">
            {{scope.row.ip}}
            <el-button type="text" size="mini" @click="queryIpAddress(scope.row)">查看地址</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="zhongduan"
          label="终端"
          width="50">
          <template slot-scope="scope">
            {{checkAgent(scope.row.userAgent).isPc?'PC':'手机'}}
          </template>
        </el-table-column>
        <el-table-column
          prop="userAgent"
          label="浏览器">
          <template slot-scope="scope">
            {{checkAgent(scope.row.userAgent).isChrome?'Chrome':(checkAgent(scope.row.userAgent).isPostman?'Postman':'其他')}}
          </template>
        </el-table-column>
        <el-table-column
          prop="serviceId"
          label="服务名"
          width="150">
        </el-table-column>
        <el-table-column
          prop="waitTime"
          label="耗时"
          width="120">
          <template slot-scope="scope">
            <span :class="getMTimeColorClass(scope.row)">
              <span v-if="getMTimeColorClass(scope.row)==='text-danger'"><i class="fa fa-exclamation-triangle"></i></span>
              {{getMTime(scope.row)}}
            </span>毫秒
          </template>
        </el-table-column>
        <el-table-column
          prop="requestTime"
          label="请求时间"
          width="100">
          <template slot-scope="scope">
            <span>{{parseTime(scope.row.requestTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          prop="opts"
          label="操作"
          width="60">
          <template slot-scope="scope">
            <el-button type="text" @click="viewInfo(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="custom-pagination"
        @current-change="query"
        :current-page.sync="queryParams.pageNumber"
        :page-size="queryParams.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableDataTotal"
        style="text-align:right;">
      </el-pagination>
    </div>

    <el-drawer
      title="日志详情"
      v-if="logInfo"
      custom-class="log-info-view"
      :visible.sync="logInfo"
      direction="rtl"
      :size="400"
      :before-close="handleClose">
      <div class="log-info-content">
        <p><span class="title-text">「{{logInfo.serviceId}}」</span> <span class="sub-text">地址：{{logInfo.path}}</span></p>
        <p class="clock-text">
          <span><i class="el-icon-alarm-clock"></i>&nbsp;请求时间：{{parseTime(logInfo.requestTime)}}</span>
          <el-divider direction="vertical"></el-divider>
          <span><i class="el-icon-alarm-clock"></i>&nbsp;返回时间：{{parseTime(logInfo.responseTime)}}</span>
        </p>
        <p class="clock-text">{{logInfo.userAgent}}</p>
        <p class="req-info">
          <el-tag :type="logInfo.httpStatus===200?'success':'danger'" size="mini">{{logInfo.httpStatus}}</el-tag>
          <el-divider direction="vertical"></el-divider>
          <el-tag type="primary" size="mini">{{logInfo.method}}</el-tag>
          <el-divider direction="vertical"></el-divider>
          <span><i class="el-icon-connection"></i>&nbsp;{{logInfo.ip}}</span>
          <el-divider direction="vertical"></el-divider>
          <span><i class="el-icon-timer"></i>&nbsp;{{getMTime(logInfo)}}毫秒</span>
        </p>
        <el-divider content-position="left">请求头</el-divider>
        <json-viewer
          :value="logInfo.headers"
          :expand-depth=5
          copyable
          theme="my-jv-theme"
          sort></json-viewer>
        <el-divider content-position="left">请求参数</el-divider>
        <json-viewer
          :value="logInfo.params"
          :expand-depth=5
          copyable
          theme="my-jv-theme"
          sort></json-viewer>
        <el-divider content-position="left">报错</el-divider>
        <json-viewer
          :value="logInfo.error"
          :expand-depth=5
          copyable
          theme="my-jv-theme"
          sort></json-viewer>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import JsonViewer from 'vue-json-viewer'
  import RouterSelect from '../../common/RouterSelect'

  export default {
    name: "index",
    components: {
      JsonViewer,RouterSelect
    },
    data() {
      return {
        loading: false,
        // 查询参数配置
        queryParams: {
          startTime:'',
          endTime: '',
          path: '',
          ip: '',
          serviceId: '',
          pageNumber: 1,
          pageSize: 10
        },
        dateRange: '',
        // 结果列表参数
        tableData: [],
        tableDataTotal: 0,
        logInfo: null
      }
    },
    watch: {
      dateRange() {
        if(this.dateRange && this.dateRange.length>0){
          this.queryParams.startTime = this.dateRange[0];
          this.queryParams.endTime = this.dateRange[1];
        }else{
          this.queryParams.startTime = '';
          this.queryParams.endTime = '';
        }
      }
    },
    mounted: function(){
      this.query();
    },
    methods: {
      query: function(currPage){
        if(!currPage)
          this.queryParams.pageNumber = 1;
        this.loading = true;
        this.api.post('/bucket-log/gateway/access/logs', this.queryParams)
          .then((data) => {
            this.tableData = data.data.records;
            this.tableDataTotal = parseInt(data.data.total);
            this.loading = false;
          });
      },
      parseTime: function(time){
        return this.$moment(time).format('YYYY-MM-DD HH:mm:ss');
      },
      parseMethod(str) {
        str = str.replace('execution(', '');
        str = str.substring(0, str.lastIndexOf(')'));
        return str;
      },
      viewInfo(row) {
        this.logInfo = row;
      },
      handleClose() {
        this.logInfo = null;
      },
      checkAgent(ua) {
          let isWindowsPhone = /(?:Windows Phone)/.test(ua),
          isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
          isAndroid = /(?:Android)/.test(ua),
          isFireFox = /(?:Firefox)/.test(ua),
          isChrome = /(?:Chrome|CriOS)/.test(ua),
          isPostman = /(?:PostmanRuntime)/.test(ua),
          isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
          isPhone = /(?:iPhone)/.test(ua) && !isTablet,
          isPc = !isPhone && !isAndroid && !isSymbian;
        return {
          isTablet: isTablet,
          isPhone: isPhone,
          isAndroid: isAndroid,
          isChrome: isChrome,
          isFireFox: isFireFox,
          isPostman: isPostman,
          isPc: isPc
        };
      },
      getMTime(row) {
        let st = row.requestTime;
        let et = row.responseTime;
        return this.$moment(et).diff(this.$moment(st));
      },
      queryIpAddress(row) {
        window.open('http://www.ip138.com/ips138.asp?ip='+row.ip+'&action=2')
      },
      getMTimeColorClass(row) {
        let t = this.getMTime(row);
        if(t < 500)
          return 'text-success';
        else if(t < 2000)
          return 'text-primary';
        else if(t < 5000)
          return 'text-warning';
        else
          return 'text-danger';
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .log-info-view {
    .el-drawer__body {
      overflow: auto;
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .log-info-content {
    margin: 0 10px 10px 10px;
    .title-text {
      font-size: 2em;
      font-weight: bold;
    }
    .sub-text {
      color: gray;
    }
    .clock-text {
      color: #c0c4cc;
    }
    .req-info {
      display: flex;
    }
  }
</style>
